"""Gunicorn configuration."""
import logging.config
import logging.handlers
import os.path
import shutil
from common.utils.log_utils import LogUtils
from common.utils.config_utils import ConfigUtils

workers = 5
LogUtils.info(f"workers 数量 {workers}")
worker_class = "gevent"
backlog = 512
access_log_format = '%(t)s %(p)s %(h)s %(r)s %(s)s %(L)s %(b)s %(f)s %(a)s'

directory = 'log'
loglevel = 'info'
if not os.path.exists(directory):
    os.mkdir(directory)

logging.config.dictConfig(
    {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "simple": {
                "format": "[%(trace_id)s]-[%(process)d] [%(asctime)s] %(levelname)s [%(filename)s:%(lineno)s] %(message)s"}
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "level": "INFO",
                "formatter": "simple",
                "stream": "ext://sys.stdout",
            },
            "info_file_handler": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "INFO",
                "formatter": "simple",
                "filename": directory + "/data.log",
                "maxBytes": 104857600,
                "backupCount": 50,
                "encoding": "utf8",
                "filters": ["trace_id_filter"]
            },
            "error_file_handler": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "ERROR",
                "formatter": "simple",
                "filename": directory + "/error.log",
                "maxBytes": 1048576000,
                "backupCount": 50,
                "encoding": "utf8",
                "filters": ["trace_id_filter"]
            }
        },
        'filters': {
            'trace_id_filter': {
                '()': 'application.filters.traceid_filter.TraceIdFilter'
            }
        },
        "loggers": {
            "my_module": {"level": "INFO", "handlers": ["console"], "propagate": "no"}
        },
        "root": {
            "level": "INFO",
            "handlers": ["error_file_handler", "info_file_handler"],
        },
    }
)

errorlog = directory + '/data.log'
accesslog = directory + '/access.log'
pidfile = 'scripts/gunicorn.pid'
bind = ":15000"
timeout = 600
capture_output = True
raw_env = [f"WORKER_CNT={workers}"]


def on_starting(server):
    prometheus_stats_dir = ConfigUtils.get_prometheus_dir()
    if os.path.exists(prometheus_stats_dir):
        shutil.rmtree(prometheus_stats_dir)
    os.mkdir(prometheus_stats_dir)


# 注册启动钩子
on_starting = on_starting
